<?php

namespace App\Http\Controllers\System;

use Exception;
use App\Models\Position;
use App\Http\Controllers\Controller;
use App\Repositories\PositionRepository;
use App\Http\Requests\System\Position\QueryResource;
use App\Http\Requests\System\Position\StoreResource;
use App\Http\Requests\System\Position\UpdateResource;
use App\Http\Requests\System\Position\QueryCollection;
use App\Http\Requests\System\Position\DestroyResource;

/**
 * 岗位管理控制器
 *
 * Date: 22/03/2018
 * @author George
 * @package App\Http\Controllers\System
 */
class PositionController extends Controller
{
	protected $positionRepository;

	/**
	 * PositionController constructor.
	 * @param PositionRepository $positionRepository
	 */
	public function __construct(PositionRepository $positionRepository)
	{
		$this->positionRepository = $positionRepository;
	}

	/**
	 * 根据公司ID获取公司所有岗位
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param QueryCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(QueryCollection $request)
	{
		$company = $request->get('company');
		$result = $this->positionRepository->getByCompany($company);
		return success($result);
	}

	/**
	 * 根据主键获取模型资源
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param QueryResource $request
	 * @param $position
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(QueryResource $request, Position $position)
	{
		return success($position);
	}

	/**
	 * 创建岗位资源
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param StoreResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
	public function store(StoreResource $request)
	{
		$attributes = $request->only(['name', 'company_id']);
		$permissions = $request->get('permissions');

		$position = $this->positionRepository->store($attributes);
		$position->permissions()->attach($permissions);
		return stored($position);
	}

	/**
	 * 更新岗位资源属性
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param UpdateResource $request
	 * @param Position $position
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \App\Repositories\GeneralException
	 */
	public function update(UpdateResource $request, Position $position)
	{
		$permissions = $request->get('permissions');
		$position = $this->positionRepository->update($position, ['name' => $request->get('name')]);
		$position = $this->positionRepository->syncPermissions($position, $permissions);
		$position->permissions = $position->permissions()->pluck('code');
		return updated($position);
	}

	/**
	 * 删除岗位资源
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param DestroyResource $request
	 * @param Position $position
	 * @return \Illuminate\Http\JsonResponse
	 * @throws Exception
	 */
	public function destroy(DestroyResource $request, Position $position)
	{
		// 移除用户表中的岗位ID
		$position->users()->update(['position_id' => null]);
		$this->positionRepository->destroy($position);
		return deleted();
	}
}
